package com.maker.mcp.business.tools;

import com.maker.mcp.business.bean.Product;
import com.maker.mcp.business.enums.ListSortType;
import com.maker.mcp.business.enums.PriceCompareEnum;
import com.maker.mcp.business.inter.ProductRepository;
import jakarta.persistence.criteria.Predicate;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Component
@RequiredArgsConstructor
public class ProductTool {

    private final ProductRepository productRepository;



    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    public static class CreateProductRequest {

        @ToolParam(description = "商品名称")
        private String productName;
        @ToolParam(description = "商品品牌")
        private String brand;
        @ToolParam(description = "商品描述(可以为空)")
        private String description;
        @ToolParam(description = "商品价格")
        private Integer price;
        @ToolParam(description = "商品库存数量")
        private Integer stock;
        @ToolParam(description = "商品状态（下架状态值为0，上架状态值为1，预售状态值为2）")
        private Integer status;
    }
    /*
    测试：请创建李宁运动鞋2025款商品，适合中老年人的运动鞋，价格229元，库存还有3400双，下架
     */
    @Tool(description = "创建/新增商品信息记录")
    public String createProduct(CreateProductRequest createProductRequest) {
        log.info("=============调用MCP工具：createProduct=============");
        log.info(String.format("参数createProductRequest为：%s",createProductRequest.toString()));
        Product product = new Product();
        BeanUtils.copyProperties(createProductRequest, product);
        //生成随机的数字
        product.setProductId(UUID.randomUUID().toString());
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        productRepository.save( product);
        return "商品创建成功";
    }
    /**
     * 删除商品记录
     * 测试：请删除编号为2dbd3cba-b12f-4935-8152-0645bbdc9ae1商品信息
     * @param productId
     * @return
     */
    @Tool(description = "根据商品ID删除商品记录")
    public String deleteProduct(String productId) {
        log.info("=============调用MCP工具：deleteProduct=============");
        log.info(String.format("参数 productId 为：%s",productId));
        productRepository.deleteById(productId);
        return "商品删除成功";
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    public static class QueryProductRequest {

        @ToolParam(description = "商品编号",required = false)
        private String productId;
        @ToolParam(description = "商品名称",required = false)
        private String productName;
        @ToolParam(description = "商品品牌",required = false)
        private String brand;
//        @ToolParam(description = "商品描述(可以为空)",required = false)
//        private String description;
        @ToolParam(description = "商品价格",required = false)
        private Integer price;
//        @ToolParam(description = "商品库存数量",required = false)
//        private Integer stock;
        @ToolParam(description = "商品状态（下架状态值为0，上架状态值为1，预售状态值为2）",required = false)
        private Integer status;
        @ToolParam(description = "查询列表的排序",required = false)
        private ListSortType sortType;
        @ToolParam(description = "比较价格大小",required = false)
        private PriceCompareEnum priceCompareType;
    }

    @Tool(description = "把排序（正序/倒序）转换为对应的枚举")
    public ListSortType  getSortType(String sort) {
        log.info("=============调用MCP工具：getSortType=============");
        log.info(String.format("参数 sort 为：%s",sort));

        if(sort.equalsIgnoreCase(ListSortType.ASC.value)){
            return ListSortType.ASC;
        }else {
            return ListSortType.DESC;
        }
    }

    @Tool(description = "把商品价格的比较（大于/小于/大于等于/小于等于/高于/低于/不高于/不低于/等于）转换为对应的枚举")
    public PriceCompareEnum  getPriceCompareType(String priceCompare) {
        log.info("=============调用MCP工具：getPriceCompareType=============");
        log.info(String.format("参数 sort 为：%s",priceCompare));

        if (priceCompare.equalsIgnoreCase(PriceCompareEnum.GREATER_THAN.value)){
            return PriceCompareEnum.GREATER_THAN;
        }else if (priceCompare.equalsIgnoreCase(PriceCompareEnum.LESS_THAN.value)){
            return PriceCompareEnum.LESS_THAN;
        }else if (priceCompare.equalsIgnoreCase(PriceCompareEnum.GREATER_THAN_OR_EQUAL_TO.value)){
            return PriceCompareEnum.GREATER_THAN_OR_EQUAL_TO;
        }else if(priceCompare.equalsIgnoreCase(PriceCompareEnum.LESS_THAN_OR_EQUAL_TO.value)){
            return PriceCompareEnum.LESS_THAN_OR_EQUAL_TO;
        }else if (priceCompare.equalsIgnoreCase(PriceCompareEnum.HIGHER_THAN.value)){
            return PriceCompareEnum.HIGHER_THAN;
        }else if (priceCompare.equalsIgnoreCase(PriceCompareEnum.LOWER_THAN.value)){
            return PriceCompareEnum.LOWER_THAN;
        }else if (priceCompare.equalsIgnoreCase(PriceCompareEnum.NOT_HIGHER_THAN.value)){
            return PriceCompareEnum.NOT_HIGHER_THAN;
        }else if (priceCompare.equalsIgnoreCase(PriceCompareEnum.NOT_LOWER_THAN.value)){
            return PriceCompareEnum.NOT_LOWER_THAN;
        }else{
            return PriceCompareEnum.EQUAL_TO;
        }

    }

    /**
     * 测试：1、请查询编号为210a5091-9f71-44e0-a680-034d22b9198b，品牌是李宁，商品是帽子，商品的状态是上架,价格不高于1000元的记录，请倒序排序输出
     * 2、查询所有的商品
     * 3、查询价格不低于1000的商品
     * @param queryProductRequest
     * @return
     */
    @Tool(description = "把排序（正序/倒序）转换为对应的枚举")
    public List< Product>  getProductList(QueryProductRequest queryProductRequest) {
        log.info("=============调用MCP工具：getProductList=============");
        log.info(String.format("参数 sort 为：%s",queryProductRequest.toString()));
        String productId = queryProductRequest.getProductId();
        String productName = queryProductRequest.getProductName();
        String brand = queryProductRequest.getBrand();
        Integer price = queryProductRequest.getPrice();
        Integer status = queryProductRequest.getStatus();
        ListSortType sortType = queryProductRequest.getSortType();
        PriceCompareEnum priceCompareType = queryProductRequest.getPriceCompareType();

        Specification<Product> spec = buildSpec(productId, productName, brand, status, price, priceCompareType);
        // 2. 动态排序
        Sort sort = Sort.unsorted();          // 默认无序
        if (sortType != null) {
            sort = switch (sortType) {
                case ASC  -> Sort.by("price").ascending();
                case DESC -> Sort.by("price").descending();
            };
        }

        // 3. 查询
        return productRepository.findAll(spec, sort);
    }

    public static Specification<Product> buildSpec(String productId,
                                                   String productName,
                                                   String brand,
                                                   Integer status,
                                                   Integer price,
                                                   PriceCompareEnum priceCompare
                                                   ) {
        return (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();

            if (StringUtils.isNotBlank(productId)) {
                list.add(cb.equal(root.get("productId"), productId));
            }
            if (StringUtils.isNotBlank(productName)) {
                list.add(cb.like(root.get("productName"), "%" + productName + "%"));
            }
            if (StringUtils.isNotBlank(brand)) {
                list.add(cb.like(root.get("brand"), "%" + brand + "%"));
            }
            if (status != null) {
                list.add(cb.equal(root.get("status"), status));
            }
            if (price != null && priceCompare != null) {
                switch (priceCompare) {
                    case GREATER_THAN->
                            list.add(cb.greaterThan(root.get("price"), price));
                    case LESS_THAN ->
                            list.add(cb.lessThan(root.get("price"), price));
                    case GREATER_THAN_OR_EQUAL_TO ->
                            list.add(cb.greaterThanOrEqualTo(root.get("price"), price));
                    case LESS_THAN_OR_EQUAL_TO ->
                            list.add(cb.lessThanOrEqualTo(root.get("price"), price));
                    case HIGHER_THAN ->
                            list.add(cb.greaterThan(root.get("price"), price));
                    case LOWER_THAN ->
                            list.add(cb.lessThan(root.get("price"), price));
                    case NOT_HIGHER_THAN ->
                            list.add(cb.lessThanOrEqualTo(root.get("price"), price));
                    case NOT_LOWER_THAN ->
                            list.add(cb.greaterThanOrEqualTo(root.get("price"), price));
                    case EQUAL_TO ->
                            list.add(cb.equal(root.get("price"), price));
                    default -> throw new IllegalArgumentException("Invalid price comparison operator: " + priceCompare);
                }
            }


            return cb.and(list.toArray(new Predicate[0]));
        };
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    public static class ModifyProductRequest {

        @ToolParam(description = "商品编号",required = false)
        private String productId;
        @ToolParam(description = "商品名称",required = false)
        private String productName;
        @ToolParam(description = "商品品牌",required = false)
        private String brand;
        @ToolParam(description = "商品描述(可以为空)",required = false)
        private String description;
        @ToolParam(description = "商品价格",required = false)
        private Integer price;
                @ToolParam(description = "商品库存数量",required = false)
        private Integer stock;
        @ToolParam(description = "商品状态（下架状态值为0，上架状态值为1，预售状态值为2）",required = false)
        private Integer status;
    }
    /**
     * 更新商品信息
     * 修改商品编号0a7b7dee-8fe4-4daa-a731-310fbd16016a信息，价格调为629，库存增加100
     * @param modifyProductRequest
     * @return
     */
    @Tool(description = "更新商品信息")
    public String  modifyProductInfo(ModifyProductRequest modifyProductRequest) {
        log.info("=============调用MCP工具：modifyProductInfo=============");
        log.info(String.format("参数 sort 为：%s",modifyProductRequest.toString()));
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        BeanUtils.copyProperties(modifyProductRequest, queryProductRequest);
        // 1. 查
        List<Product> productList = this.getProductList(queryProductRequest);
        if (productList != null && productList.size() ==1) {
            Product product = productList.get(0);
            BeanUtils.copyProperties(modifyProductRequest, product);
            product.setUpdateTime(LocalDateTime.now());
            productRepository.save(product);
            return "商品信息更新成功";
        }else {
            return "商品编号:"+modifyProductRequest.getProductId()+"不存在";
        }

    }











}
